package cn.alpha.common.springmvc;

import java.util.LinkedList;
import java.util.List;

import org.springframework.core.MethodParameter;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * 用于Spring MVC在解析handler方法参数的时候将逗号隔开的字符串拆分成数据形式，
 * 正确的处理带有StringSplitArgument注解的参数
 * @author liushx
 *
 */
public class StringSplitArgumentResolver implements HandlerMethodArgumentResolver {

	public Object resolveArgument(MethodParameter parameter,
			ModelAndViewContainer mavContainer, NativeWebRequest webRequest,
			WebDataBinderFactory binderFactory) throws Exception {
	
		String paramName = parameter.getParameterName();
		System.out.println(parameter);
		String idStr = webRequest.getParameter(paramName);
		String[] ids = idStr.split("\\,");
		List<Long> res=new LinkedList<Long>();
        for (int idx = 0; idx < ids.length; idx++) {
        	if(!StringUtils.isEmpty(ids[idx]))
        		res.add(Long.parseLong(ids[idx]));
        }
		return res;
	}

	public boolean supportsParameter(MethodParameter parameter) {
	
		return parameter.getParameterAnnotation(StringSplitArgument.class) != null;
	}

}
